package com.example.demo.config.activiti;

import com.example.demo.config.ftpclient.FTPUtil;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipInputStream;

@Component
@AutoConfigureAfter(ActivitiConfig.class)
@Slf4j
public class ActivitiBPMNSConfig implements CommandLineRunner {
    private static final String sql = "SELECT wf.bpmn_address as bpmn_address " +
            "FROM work_flowftpaddress wf " +
            "WHERE wf.valid = \"OPEN\"";

    private static final String url = "127.0.0.1";
    private static final Integer port = 21;
    private static final String username = "Anonymous";
    private static final String password = "";

    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;
    @Autowired
    private ProcessEngine processEngine;

    public void runDemo() {
        List<String> list = new ArrayList<>();
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.createStatement();
            statement.execute(sql);
            rs = statement.executeQuery(sql);
            log.info("执行SQL：" + sql);
            while (rs.next()) {
                list.add(rs.getString("bpmn_address"));
            }
        } catch (SQLException e) {
            log.error(e.getMessage());
        } finally {
            try {
                if (!(rs != null && rs.isClosed())) rs.close();
                if (!(statement != null && statement.isClosed())) statement.close();
                if (!(connection != null && connection.isClosed())) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (!(list == null || list.size() < 1)) {
            List<InputStream> inputStreams =
                    FTPUtil.fileInputStream(url, port, username, password, list);

            //创建部署对象
            DeploymentBuilder deploymentBuilder = processEngine.getRepositoryService()//获取流程定义和部署对象相关的Service
                    .createDeployment();
            //部署流程文件
            for (InputStream inputStream : inputStreams) {
                ZipInputStream zipInputStream = new ZipInputStream(inputStream);
                deploymentBuilder.addZipInputStream(zipInputStream);
            }
            Deployment deployment = deploymentBuilder.deploy();
            log.info(">>>>>>>>>>>>>>>>>>>>>>>>>> deployment.id : " + deployment.getId());
        }
    }

    public static List<String> getAddressFromDBHandle(DataSource dataSource) throws SQLException {
        List<String> list = new ArrayList<>();
        Statement statement = null;
        ResultSet rs = null;
        statement = dataSource.getConnection().createStatement();
        statement.execute(sql);
        rs = statement.executeQuery(sql);
        log.info("执行SQL：" + sql);
        while (rs.next()) {
            String address = rs.getString("bpmn_address");
            if (password == null || password.isEmpty()) {
                address = "ftp://" + url
                        + ":" + port + "/" +address;
            }else {
                //ftp://DNCS:DNCS@10.217.90.120
                address = "ftp://" + username + ":"
                        + password + "@"
                        + url
                        + ":" + port + "/" +address;
            }
            list.add(address);
        }

        if (!(rs != null && rs.isClosed())) rs.close();
        if (!(statement != null && statement.isClosed())) statement.close();

        return list;
    }

    public void runResourceDemo() throws SQLException, IOException {
        List<String> ftpAddress = getAddressFromDBHandle(dataSource);
        int num = ftpAddress == null ? 0 : ftpAddress.size();
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>> 需要部署流程文件数 : " + num);
        if (ftpAddress != null && ftpAddress.size() > 0) {
            //创建部署对象
            //获取流程定义和部署对象相关的Service
            DeploymentBuilder deploymentBuilder = processEngine.getRepositoryService()
                    .createDeployment();
            log.info(">>>>>>>>>>>>>>>>>>>>>>>>>> 以zip压缩包方式加载部署。");
            for (String address : ftpAddress) {
                UrlResource urlResource = new UrlResource(address);
                deploymentBuilder = deploymentBuilder
                        .addZipInputStream(new ZipInputStream(urlResource.getInputStream()));
            }
            Deployment deployment = deploymentBuilder.deploy();
            log.info(">>>>>>>>>>>>>>>>>>>>>>>>>> 部署的唯一标识 : " + deployment.getId());
        }
    }

    @Override
    public void run(String... args) throws Exception {
        runResourceDemo();
    }
}
